// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT

package exporter

import (
	"net/http"
	"sync"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"

	"uos_uwsgi_exporter/internal/config"
	"uos_uwsgi_exporter/internal/metrics"
)

// Exporter uWSGI导出器
type Exporter struct {
	config    *config.Config
	collector *metrics.Collector
	registry  *prometheus.Registry
	mu        sync.RWMutex
}

// New 创建新的导出器
func New(cfg *config.Config) *Exporter {
	// 创建注册表
	registry := prometheus.NewRegistry()

	// 创建收集器
	collector := metrics.NewCollector(cfg)

	// 注册收集器
	registry.MustRegister(collector)

	return &Exporter{
		config:    cfg,
		collector: collector,
		registry:  registry,
	}
}

// HandleMetrics 处理指标请求
func (e *Exporter) HandleMetrics(w http.ResponseWriter, r *http.Request) {
	e.mu.RLock()
	defer e.mu.RUnlock()

	// 使用Prometheus的HTTP处理器
	handler := promhttp.HandlerFor(e.registry, promhttp.HandlerOpts{})
	handler.ServeHTTP(w, r)
}

// UpdateConfig 更新配置
func (e *Exporter) UpdateConfig(cfg *config.Config) {
	e.mu.Lock()
	defer e.mu.Unlock()

	e.config = cfg
	e.collector.UpdateConfig(cfg)
}
